import { RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router'
import { userStore } from '@/store'
import { ElMessage } from 'element-plus'
const routes:RouteRecordRaw[] = [
    {
        path:'/',
        redirect:'/login',
    },
    {
        path:'/login',
        name:'login',
        component:()=>import("@/views/login/login.vue"),
        meta:{
            require_auth:false,
            title:'登录'
        }
    },
    {
        path:'/404',
        name:'404',
        component:()=>import('@/views/resultpage/nopage.vue')
    },
]

const router = createRouter({
    routes,
    history:createWebHashHistory()
})

// 全局解析守卫
// 路由是否已添加标记
let initstatus = false;
router.beforeResolve(async (to,_form,next)=>{
    const routeinit = async function (){
        await userstore.getmenus()
        initstatus = true
    }
    const userstore = userStore();
    if(userstore.status){
        if(!initstatus){
            // 添加路由
            await routeinit()
            router.addRoute(
                {
                    path:'/',
                    name:'home',
                    component:()=>import("@/views/body.vue"),
                    meta:{
                        require_auth:true,
                        title:'主页'
                    },
                    children:userstore.menus as RouteRecordRaw[]
                }
            );
            // console.log(to);
            return next({...to,replace:true})
        }else{
            if(to.path == '/login'){
                return next()
            }
            // 无路由跳转404
            const routes = router.getRoutes();
            let arr = routes.filter(e=>{
                return e.path == to.path
            })
            if(arr.length==0){
                return next('/404')
            }
            return next()
        }
    }else{
        localStorage.clear();
        ElMessage({
            message:'未登录！',
            icon:'close'
        })
        if(to.path == '/login'){
            return next()
        }else{
            return next('/login')
        }
    }
})


router.beforeEach(async (_to,_form,next)=>{
    // console.log(to)
    return next()
})

router.afterEach((to)=>{
    // console.log(to)
    if(to.meta.title){
        document.title = to.meta.title as string
    }
})

router.onError((_handler)=>{
    
})


export default router;